package com.company.project.utils;

import lombok.extern.slf4j.Slf4j;
import java.util.*;

import org.apache.commons.codec.digest.DigestUtils;

@Slf4j
public class MD5Utils {

    private static final String SECRET_KEY = "dfasuiyhkuhjk2t5290wouojj2020eeqwqdfd";
    private static final String SIGN_KEY = "sign";

    /**
     * 转换成对应的MD5信息
     *
     * @param paramMap
     * @return
     */
    public static String stringToMD5(Map<String, String> paramMap, String timestamp) {
        String covertString = covertParamMapToString(paramMap, timestamp);
        String md5code = DigestUtils.md5Hex(covertString);
//        log.error("正确的Sign: {} ", md5code);
        return md5code;
    }

    /**
     * 转换成对应的string信息
     *
     * @param paramMap
     * @return
     */
    private static String covertParamMapToString(Map<String, String> paramMap, String timestamp) {
        String resultStr = "";
        if (CommonUtils.isNotNull(paramMap) && paramMap.size() > 0) {
            Set<String> sets = paramMap.keySet();
            List<String> valueList = new ArrayList<>();
            for (String key : sets) {
                if (key.equals(SIGN_KEY)) {
                    continue;
                }
                if (paramMap.get(key) instanceof String) {
                    Object value = paramMap.get(key);
                    valueList.add(value.toString());
                }
            }
            // 此处可以使用TreeMap
            Collections.sort(valueList);
            for (String str : valueList) {
                resultStr = resultStr + str;
            }
        }
        resultStr = resultStr + SECRET_KEY + timestamp;
//        log.error("签名串:" + resultStr);
        return resultStr;
    }



}

